package com.jch.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jch.eduservice.Listener.SubjectExcelListener;
import com.jch.eduservice.entity.EduSubject;
import com.jch.eduservice.entity.excel.SubjectData;
import com.jch.eduservice.entity.excel.subject.OneSubject;
import com.jch.eduservice.entity.excel.subject.TwoSubject;
import com.jch.eduservice.mapper.EduSubjectMapper;
import com.jch.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author jch
 * @since 2024-12-08
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try{
          InputStream in=file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
           e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        // 获取一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);
        // 获取二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> TwoSubjectList = baseMapper.selectList(wrapperTwo);
        //创建集合封装最终的数据
        List<OneSubject> finalSubjectList = new ArrayList<>();
        //封装一级分类
        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
         /* oneSubject.setId(eduSubject.getId());
            oneSubject.setTitle(eduSubject.getTitle());*/
            BeanUtils.copyProperties(eduSubject,oneSubject);
            List<TwoSubject> twoSubjectList=new ArrayList<>();
            //封装二级分类
            for (EduSubject subject : TwoSubjectList) {
                TwoSubject twoSubject=new TwoSubject();
                 /* twoSubject.setId(subject.getId());
                    twoSubject.setTitle(subject.getTitle());*/
                BeanUtils.copyProperties(subject,twoSubject);
                if(subject.getParentId().equals(oneSubject.getId())){
                    twoSubjectList.add(twoSubject);
                }

            }
            oneSubject.setChildren(twoSubjectList);
            finalSubjectList.add(oneSubject);
        }

        return finalSubjectList;
    }
}
